package zz.app.jmhviewer.JMH;

import android.graphics.Color;
import android.util.JsonReader;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import zz.app.jmhviewer.OnDownloadListener;

/**
 * Created by zz on 2018/1/31 21:00.
 */

public class JMHUtils {
    private static final float TEXT_SIZE_SCALE=0.45f;
    private static final float CANVAS_TEXT_SIZE_SCALE =1.1f ;

    public static ArrayList<JMHJsonData> getPlayList(String host) throws IOException {
        ArrayList<JMHJsonData> ret = new ArrayList<>();
        try {
            URL url = new URL("http://"+host+"/musicdata.json");
            URLConnection connection = url.openConnection();
            JsonReader reader = new JsonReader(new InputStreamReader(connection.getInputStream()));
            reader.beginObject();
            reader.setLenient(true);
            while (reader.hasNext()) {
                String name = reader.nextName();
                if (name.equals("music")) {
                    reader.beginArray();
                    while (reader.hasNext()) {
                        JMHJsonData data=new JMHJsonData();
                        reader.beginObject();
                        while (reader.hasNext()) {
                            String s = reader.nextName();
                            if (s.equals("name")) {
                                data.name = reader.nextString();
                            } else if (s.equals("ver")) {
                                data.ver = reader.nextInt();
                            }

                        }
                        ret.add(data);
                        reader.endObject();
                    }
                    reader.endArray();
                }
            }
            reader.endObject();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        int i = 0;
        return ret;
    }

    public static JMHHtmlData getHtmlData(String host,String name) throws IOException {
        Document document = Jsoup.connect("http://"+host+"/"+name+"/page.html").get();
        JMHHtmlData ret = new JMHHtmlData();
        ArrayList<JMHHtmlKashiData> dataArrayList = new ArrayList<>();
        ret.title = document.getElementsByClass("title").get(0).html();
        ret.artist = document.getElementsByClass("artist").get(0).html();
        Elements holders = document.getElementsByClass("holder");
        for (Element holder : holders) {
            JMHHtmlKashiData data = new JMHHtmlKashiData();
            data.time = Integer.parseInt(holder.attr("id"));
            String kashiandkana = holder.getElementsByClass("kashi").get(0).html();
            String translate = holder.getElementsByClass("translate").get(0).html();
            if (translate.equals("<br>"))
                translate = "";
            data.translate = translate;
            kashiandkana=kashiandkana.replaceAll("\n","");
            StringBuilder kashi = new StringBuilder();
            int k = 0;
            for (int i = 0; i < kashiandkana.length(); i++) {
                String s = kashiandkana.substring(i);
                if (!s.startsWith("<ruby>")) {
                    kashi.append(kashiandkana.charAt(i));
                    k++;
                } else {
                    int j = s.indexOf("</ruby>");
                    String ruby = s.substring(0, j + 7);
                    Document document1 = Jsoup.parse(ruby);
                    String s1 = document1.getElementsByTag("ruby").get(0).html();
                    int m = s1.indexOf("<rp>");
                    s1 = s1.substring(0, m);
                    kashi.append(s1);
                    JMHKana kana = new JMHKana();
                    kana.content = document1.getElementsByClass("kana").get(0).html();
                    kana.start = k;
                    kana.end = k + s1.length();
                    k += s1.length();
                    data.kanas.add(kana);
                    i += j + 6;
                }
            }
            data.kashi=kashi.toString();
            dataArrayList.add(data);
        }
        ret.kashiData = dataArrayList;
        return ret;
    }

    public static JMHCssData getCssData(String host, String name) throws IOException {
        JMHCssParser parser = new JMHCssParser("http://" + host + "/" + name + "/style.css");
        JMHCssData ret = new JMHCssData();
        String s = parser.getValueByClassAndKey("title", "font-size");
        s = s.substring(0, s.length() - 2);
        ret.titleSize = convertSize(Float.parseFloat(s), false);
        s = parser.getValueByClassAndKey("artist", "font-size");
        s = s.substring(0, s.length() - 2);
        ret.artistSize = convertSize(Float.parseFloat(s), false);
        s = parser.getValueByClassAndKey("kashi", "font-size");
        s = s.substring(0, s.length() - 2);
        ret.kashiSize = convertSize(Float.parseFloat(s), true);
        s = parser.getValueByClassAndKey("kashicurrent", "font-size");
        s = s.substring(0, s.length() - 2);
        ret.currentKashiSize = convertSize(Float.parseFloat(s), true);
        s = parser.getValueByClassAndKey("translate", "font-size");
        s = s.substring(0, s.length() - 2);
        ret.translateSize = convertSize(Float.parseFloat(s), true);
        s = parser.getValueByClassAndKey("translatecurrent", "font-size");
        s = s.substring(0, s.length() - 2);
        ret.currentTranslateSize = convertSize(Float.parseFloat(s), true);
        s = parser.getValueByClassAndKey("title", "color");
        ret.titleColor = convertWebColor(s);
        s = parser.getValueByClassAndKey("artist", "color");
        ret.artistColor = convertWebColor(s);
        s = parser.getValueByClassAndKey("body", "background-color");
        ret.backgroundColor = convertWebColor(s);
        s = parser.getValueByClassAndKey("kashi", "color");
        ret.kashiColor = convertWebColor(s);
        s = parser.getValueByClassAndKey("kashicurrent", "color");
        ret.currentKashiColor = convertWebColor(s);
        s = parser.getValueByClassAndKey("translate", "color");
        ret.translateColor = convertWebColor(s);
        s = parser.getValueByClassAndKey("kana", "color");
        ret.kanaColor = convertWebColor(s);
        s = parser.getValueByClassAndKey("animate", "transition");
        s = s.substring(0, s.length() - 2);
        ret.animeTime = Integer.parseInt(s);
        ret.backgroundImage1 = "http://" + host + "/" + name + "/background.png";
        ret.backgroundImage2 = "http://" + host + "/" + name + "/background2.png";

        return ret;
    }

    public static String getMusicPath(String host,String name){
        return "http://"+host+"/"+name+"/music.mp3";
    }

    private static int convertWebColor(String s) {
        int r,g,b;
        String s1=s.substring(1,3);
        r=convertHexToInt(s1);
        s1=s.substring(3,5);
        g=convertHexToInt(s1);
        s1=s.substring(5,7);
        b=convertHexToInt(s1);
        return Color.rgb(r,g,b);
    }

    private static int convertHexToInt(String s1) {
        int ret=0;
        char c=s1.charAt(0);
        if(c>='A'){
            c-='A';
            c+=10;
        }else{
            c-='0';
        }
        ret+=c*16;
        c=s1.charAt(1);
        if(c>='A'){
            c-='A';
            c+=10;
        }else{
            c-='0';
        }
        return ret+c;
    }

    public static String getPicData(String host, String name,String which, OnDownloadListener listener) {
        int bkgndLong = 0;
        InputStream bkgndStream = null;
        String downLoad = null;
        try {
            if (which.equals("vert")) {
                URL url = new URL("http://" + host + "/" + name + "/background2.jpg");
                URLConnection connection = url.openConnection();
                bkgndLong = connection.getContentLength();
                bkgndStream = connection.getInputStream();
            }
            if (which.equals("hori")) {
                URL url = new URL("http://" + host + "/" + name + "/background.jpg");
                URLConnection connection = url.openConnection();
                bkgndLong = connection.getContentLength();
                bkgndStream = connection.getInputStream();
            }
        } catch (IOException ignored) {

        }
        int totalDownload = 0;
        byte[] buffer = new byte[4096];
        int i;
        FileOutputStream fos;
        if (bkgndStream != null) {
            try {
                File bkgndFile = new File(System.getProperty("java.io.tmpdir") + File.separator + "bkgnd-" + which + ".jpg");
                downLoad = bkgndFile.getAbsolutePath();
                fos = new FileOutputStream(bkgndFile);
                while ((i = bkgndStream.read(buffer, 0, 4096)) != -1) {
                    fos.write(buffer, 0, i);
                    totalDownload += i;
                    if (listener != null) listener.onDownload(totalDownload, bkgndLong);

                }
                fos.close();
            } catch (IOException ignored) {

            }
        }
        if (totalDownload >= bkgndLong)
            return downLoad;
        else
            return null;

    }

    private static float convertSize(float value,boolean isCanvas) {
        if (!isCanvas)
            return value * TEXT_SIZE_SCALE;
        else
            return value * CANVAS_TEXT_SIZE_SCALE;
    }

    public static String getMusicData(String host, String name, OnDownloadListener listener) throws IOException {
        InputStream musicStream=null;
        String downLoad=null;
        int totalLength=0;
        try {
            URL url = new URL("http://" + host + "/" + name + "/music.mp3");
            URLConnection connection = url.openConnection();
            musicStream=connection.getInputStream();
            totalLength=connection.getContentLength();
        }catch(IOException ignored){

        }
        int totalDownload=0;
        byte[] buffer=new byte[4096];
        int i;
        FileOutputStream fos;
        if(musicStream!=null) {
            try {
                File bkgndFile =new File(System.getProperty("java.io.tmpdir")+File.separator+"music.png");
                downLoad = bkgndFile.getAbsolutePath();
                fos = new FileOutputStream(bkgndFile);
                while ((i = musicStream.read(buffer, 0, 4096)) != -1) {
                    fos.write(buffer, 0, i);
                    totalDownload += i;
                    if (listener != null) listener.onDownload(totalDownload, totalLength);

                }
                fos.close();
            }catch (IOException ignored){

            }
        }

        return downLoad;
    }
}
